<template>
  <div class="orders-view">
    <h1>📋 订单管理</h1>

    <el-card class="toolbar-card">
      <div class="toolbar">
        <el-input v-model="query.keyword" placeholder="订单号/用户/演出ID" clearable class="w-300" @keyup.enter.native="loadOrders" />
        <el-input v-model.number="query.userId" placeholder="用户ID" clearable class="w-160" />
        <el-input v-model.number="query.eventId" placeholder="演出ID" clearable class="w-160" />
        <el-select v-model="query.status" placeholder="状态" class="w-120">
          <el-option :value="null" label="全部" />
          <el-option :value="1" label="待支付" />
          <el-option :value="2" label="已支付" />
          <el-option :value="3" label="已取消" />
        </el-select>
        <el-select v-model="query.sortBy" class="w-140">
          <el-option value="createdAt" label="按创建时间" />
          <el-option value="totalAmount" label="按金额" />
          <el-option value="status" label="按状态" />
        </el-select>
        <el-select v-model="query.order" class="w-100">
          <el-option value="DESC" label="降序" />
          <el-option value="ASC" label="升序" />
        </el-select>
        <el-select v-model="query.size" class="w-120" @change="handleSizeChange">
          <el-option :value="10" label="每页10条" />
          <el-option :value="20" label="每页20条" />
          <el-option :value="50" label="每页50条" />
        </el-select>
        <el-button type="primary" @click="loadOrders" :loading="loading">查询</el-button>
        <el-button @click="resetFilters" :disabled="loading">重置</el-button>
      </div>
    </el-card>

    <el-card>
      <div class="batch-bar">
        <el-button :disabled="selected.length===0" @click="batchUpdateStatus(2)" type="primary">批量标记已支付</el-button>
        <el-button :disabled="selected.length===0" @click="batchUpdateStatus(3)" type="danger">批量取消订单</el-button>
      </div>

      <el-table :data="orders" border stripe v-loading="loading" style="width: 100%" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="订单号" min-width="160" />
        <el-table-column prop="userId" label="用户ID" width="100" />
        <el-table-column prop="eventId" label="演出ID" width="100" />
        <el-table-column prop="status" label="状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'warning' : row.status === 2 ? 'success' : 'info'">
              {{ statusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="金额" width="120">
          <template #default="{ row }">¥{{ row.totalAmount ?? 0 }}</template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" min-width="160">
          <template #default="{ row }">{{ formatDate(row.createdAt) }}</template>
        </el-table-column>
        <el-table-column label="操作" min-width="220">
          <template #default="{ row }">
            <div class="action-cell">
              <el-button size="small" type="primary" text @click="viewOrder(row)">查看</el-button>
              <el-button-group>
                <el-button size="small" type="primary" @click="updateStatus(row, 2)">标记已支付</el-button>
                <el-button size="small" type="danger" @click="updateStatus(row, 3)">取消订单</el-button>
              </el-button-group>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size="query.size"
          :current-page="query.page + 1"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { orderAPI } from '@/api'

const loading = ref(false)
const orders = ref([])
const total = ref(0)
const query = ref({ page: 0, size: 10, keyword: '', userId: null, eventId: null, status: null, sortBy: 'createdAt', order: 'DESC' })
const selected = ref([])

function formatDate(dt) { if (!dt) return ''; return new Date(dt).toLocaleString('zh-CN') }
function statusText(s) { return s === 1 ? '待支付' : s === 2 ? '已支付' : s === 3 ? '已取消' : '未知' }

async function loadOrders() {
  try {
    loading.value = true
    const params = { ...query.value }
    // 去除空筛选项，保持后端参数简洁
    Object.keys(params).forEach(k => { if (params[k] === null || params[k] === '') delete params[k] })
    const resp = await orderAPI.getOrderList(params)
    const content = resp?.data?.content || resp?.content || resp || []
    orders.value = Array.isArray(content) ? content : []
    total.value = resp?.data?.totalElements ?? resp?.totalElements ?? orders.value.length
  } catch (err) {
    ElMessage.error(`加载订单失败：${err?.message || '请求错误'}`)
  } finally {
    loading.value = false
  }
}

function resetFilters() { query.value = { page: 0, size: 10, keyword: '', userId: null, eventId: null, status: null, sortBy: 'createdAt', order: 'DESC' }; loadOrders() }
function handleSizeChange() { query.value.page = 0; loadOrders() }
function handlePageChange(p) { query.value.page = p - 1; loadOrders() }

function viewOrder(row) { ElMessage.info(`查看订单：${row.orderNo}`) }
async function updateStatus(row, status) {
  try {
    await orderAPI.updateOrderStatus(row.id || row.orderNo, status)
    ElMessage.success('状态已更新')
    loadOrders()
  } catch (err) {
    ElMessage.error(`更新失败：${err?.message || '请求错误'}`)
  }
}

function handleSelectionChange(rows) { selected.value = rows || [] }
async function batchUpdateStatus(status) {
  if (!selected.value.length) return
  try {
    await ElMessageBox.confirm(`确认对选中${selected.value.length}个订单执行更新？`, '提示', { type: 'warning' })
    const ids = selected.value.map(o => o.id || o.orderNo)
    await Promise.all(ids.map(id => orderAPI.updateOrderStatus(id, status)))
    ElMessage.success('批量更新成功')
    selected.value = []
    loadOrders()
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error(`批量更新失败：${err?.message || '请求错误'}`)
    }
  }
}

onMounted(loadOrders)
</script>

<style scoped>
.orders-view { padding: 20px; }
.toolbar-card { margin-bottom: 12px; }
.toolbar { display: flex; gap: 12px; align-items: center; }
.w-300 { width: 300px; }
.w-160 { width: 160px; }
.w-140 { width: 140px; }
.w-100 { width: 100px; }
.w-120 { width: 120px; }
.table-footer { display: flex; justify-content: flex-end; padding-top: 12px; }
.batch-bar { padding-bottom: 8px; display: flex; gap: 12px; }
 .action-cell { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
</style>